package com.Jee.JeeHttp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServerV1 {
    //Http底层基于TCP实现
    private ServerSocket serverSocket = null;

    public HttpServerV1(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true) {
            //1，获取连接
            Socket clientSocket = serverSocket.accept();
            //2，处理连接（使用短连接的方式实现）
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    handler(clientSocket);
                }
            });
        }
    }

    public void handler(Socket clientSocket) {
        //http协议是文本协议，所以使用字符流来处理
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))){

            //1，下面的操作严格按照HTTP协议来操作
            //  1、1 解析首行，三个部分使用空格切分,readLine读取出来的格式是 GET  [localhost:port省略了]/xxx HTTP/1.1
            //System.out.println(bufferedReader.readLine());
            String firstLine = bufferedReader.readLine();
            String[] firstLineTokens = firstLine.split(" ");
            String method = firstLineTokens[0];
            String url = firstLineTokens[1];
            String version = firstLineTokens[2];

            //  1、2 解析header，按行读取，然后按照冒号空格来分割键值对
            HashMap<Object, Object> headers = new HashMap<>();
            String line = " ";
            //readLine 读取一行内容，是会自动去掉换行符的，对于空行来说，去掉了换行符，就变成了空字符串
            while ((line = bufferedReader.readLine())!=null && line.length()!=0){
                String[] split = line.split(":");
                headers.put(split[0],split[1]);
            }

            //  1、3 解析body
            System.out.printf("%s %s %s\n",method,url,version);
            System.out.println(headers);

            //2，返回响应
            bufferedWriter.write(version+" 200 OK\n");
            String resp = "<h1>test</h1>";
            bufferedWriter.write("Content-Type: text/html\n");
            bufferedWriter.write("Content-Length: " + resp.getBytes().length + "\n");
            bufferedWriter.write("\n");
            bufferedWriter.write(resp);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public static void main(String[] args) throws IOException {
        HttpServerV1 httpServerV1 = new HttpServerV1(8081);
        httpServerV1.start();
    }
}
